package com.chookss.tiku

import android.os.Bundle
import android.view.WindowManager
import com.chookss.base.StaticClass
import com.chookss.tiku.entity.Subject
import com.chookss.tiku.view.SubjectView
import com.chookss.tools.NavigationTools
import com.johnrambo.ktea.common.createLoadingDialog
import com.johnrambo.ktea.ktExtends.ShareUtils
import com.johnrambo.ktea.ktExtends.observe
import com.lvgroup.hospital.base.BaseAct
import errorToast

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/30
 * Note:
 */
abstract class BaseSubjectActivity<T : SubjectAnswerViewModel> : BaseAct() {
    protected val viewModel: T by lazy {
        createViewModel()
    }

    abstract fun subjectView(): SubjectView

    abstract fun createViewModel(): T

    protected var subjectIndex = 0
    private var lpFlag:String = "" //0禁止1正常

    protected val loadingProgress by lazy {
        createLoadingDialog(this) {}
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        subjectIndex = savedInstanceState?.getInt("subjectIndex") ?: 0
        lpFlag = ShareUtils().getString(this, StaticClass.LP_FLAG, "1")
        //禁止截屏
        if ("0".equals(lpFlag)) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }
        //顶部状态栏 处理
        NavigationTools.saveUseRecord(this, "1", "13")
        super.onCreate(savedInstanceState)
    }

    override fun onContentChanged() {
        super.onContentChanged()
        gotoSubject(subjectIndex)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("subjectIndex", subjectIndex)
    }


    protected fun refreshSubject() {
        gotoSubject(subjectIndex)
    }

    protected open fun gotoSubject(index: Int) {
        loadingProgress.show()
        viewModel.getSubject(index).observe(this, {
            loadingProgress.dismiss()
            if (it.error != null) {
                errorToast(it.error.message ?: "")
            } else if (it.data != null) {
                subjectIndex = index
                    getSubjectAnswers(index, it.data)

            } else {
                onShowSubjectsLoaded(false)
            }
        })
    }


    open fun onShowSubjectsLoaded(isShowData: Boolean) {
        //是否有数据
    }

    protected fun getSubjectAnswers(index: Int, data: Subject) {
        viewModel.getSubjectAnswer(data.subjectCode).observe(this, {
            if (it.error != null) {
                errorToast(it.error.message ?: "")
            } else if (it.data != null) {
//                if ( data.subjectCode!=subjectView().subject?.subjectCode) {
                    subjectView().subject = data
                    subjectView().answers = it.data
                    onSubjectLoaded(index, data)
                    onShowSubjectsLoaded(true)
//                }
            }
        })
    }

    override fun initData() {

    }

    abstract fun onSubjectLoaded(index: Int, subject: Subject)

}